package com.chaofan.emos.wx.config;

import com.chaofan.emos.wx.exception.EmosException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * @author 李超凡
 * @since 2022/2/27 15:16
 */
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String exceptionHandler(Exception e) {
        log.error("执行异常", e);
        if (e instanceof MethodArgumentNotValidException exception) {
            return Objects.requireNonNull(exception.getBindingResult().getFieldError()).getDefaultMessage();
        } else if (e instanceof EmosException exception) {
            return exception.getMsg();
        } else if (e instanceof UnauthorizedException exception) {
            return "你不具备相关权限";
        } else {
            return "你不具备相关权限";
        }
    }
}
